import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const news = await db.get<any>(`
      SELECT 
        id, title, summary, content, image, images, category, tags, author,
        publish_date as publishDate, is_published as isPublished, 
        is_pinned as isPinned, view_count as viewCount,
        created_at as createdAt, updated_at as updatedAt
      FROM news WHERE id = ?
    `, [params.id]);
    
    if (news && news.images) {
      news.images = JSON.parse(news.images);
    } else {
      news.images = [];
    }
    
    if (!news) {
      return NextResponse.json({
        success: false,
        error: 'News not found'
      }, { status: 404 });
    }
    
    return NextResponse.json({
      success: true,
      data: news
    });
  } catch (error) {
    console.error('Error fetching news:', error);
    return NextResponse.json({
      success: false,
      error: 'Failed to fetch news'
    }, { status: 500 });
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const data = await request.json();
    const now = new Date().toISOString();
    
    await db.run(`
      UPDATE news SET 
        title = ?, summary = ?, content = ?, image = ?, images = ?,
        category = ?, author = ?, publish_date = ?, 
        is_published = ?, is_pinned = ?, updated_at = ?
      WHERE id = ?
    `, [
      data.title, data.summary || '', data.content, 
      data.image || null, JSON.stringify(data.images || []), data.category || 'news',
      data.author || 'admin', data.publishDate || now,
      data.isPublished ? 1 : 0, data.isPinned ? 1 : 0,
      now, params.id
    ]);
    
    return NextResponse.json({
      success: true,
      data: { id: params.id, ...data }
    });
  } catch (error) {
    console.error('Error updating news:', error);
    return NextResponse.json({
      success: false,
      error: 'Failed to update news'
    }, { status: 500 });
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    await db.run(`DELETE FROM news WHERE id = ?`, [params.id]);
    
    return NextResponse.json({
      success: true,
      message: 'News deleted successfully'
    });
  } catch (error) {
    console.error('Error deleting news:', error);
    return NextResponse.json({
      success: false,
      error: 'Failed to delete news'
    }, { status: 500 });
  }
}